package com.jalonjia.paste.controller;

import com.jalonjia.paste.pojo.Paste;
import com.jalonjia.paste.service.PasteService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@Slf4j
@Controller
public class PasteController {
    @Value("${paste.keepDays}")
    private long keepDays;
    @Resource
    PasteService pasteService;

    @GetMapping("/p")
    public String index() {
        return "index";
    }

    @PostMapping("/p")
    public String paste(Paste paste) {
        if (StringUtils.isEmpty(paste.getCode())) {
            return "index";
        }
        paste.setTimeout(TimeUnit.DAYS.toMillis(keepDays));
        log.info("Add: {}", paste);
        pasteService.add(paste);
        return "redirect:/p/" + paste.getId();
    }

    @GetMapping("/p/{key}")
    public ModelAndView id(ModelAndView mv, @PathVariable("key") String key) {
        Paste paste = pasteService.getById(key);
        mv.addObject("paste", paste);
        if (paste == null) {
            mv.setViewName("404");
        } else {
            mv.setViewName("paste");
        }
        return mv;
    }
}
